﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;
using System.EnterpriseServices;
using System.Web.Services;

public partial class DeliverGoodsManagement_DealLogDetail : System.Web.UI.Page
{
    public event RepeaterCommandEventHandler ItemCommand;

    public List<string> Selected
    {
        get
        {
            List<string> l = new List<string>();
            foreach (RepeaterItem item in rptIMPORTBILL_ALIPAYDETAIL.Items)
            {
                CheckBox cb = item.FindControl("chkChoose") as CheckBox;
                if (cb != null && cb.Checked)
                {
                    HiddenField fld = item.FindControl("hfIMPORTBILL_ALIPAYDETAIL") as HiddenField;
                    if (fld != null)
                    {
                        string id = fld.Value;
                        l.Add(id);
                    }
                }
            }
            return l;
        }
    }

    private string OrderId
    {
        get
        {
            string orderId = "";
            if (ViewState["OrderId"] != null)
            {
                orderId = ViewState["OrderId"].ToString();
            }
            return orderId;

        }
        set
        {
            ViewState["OrderId"] = value;
        }
    }

    private string Code
    {
        get
        {
            return Request.QueryString["code"] != null ? Request.QueryString["code"].ToString() : "";
        }
    }

    private string PayType
    {
        get
        {
            string payType = "";
            if (ViewState["PayType"] != null)
            {
                payType = ViewState["PayType"].ToString();
            }
            return payType;
        }
        set
        {
            ViewState["PayType"] = value;
        }
    }

    private DataSet DealLogDetails
    {
        get
        {
            DataSet ds = null;
            if (ViewState["DealLogDetails"] != null)
            {
                ds = (DataSet)ViewState["DealLogDetails"];
            }
            return ds;
        }
        set
        {
            ViewState["DealLogDetails"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            AspNetPager1.PageSize = int.Parse(ConfigurationManager.AppSettings["RowCountPerPage"]);
            BindDealLogMain();
            BindDealLogDetail();
            DealLogDetails = new BLL.IMPORTBILL_ALIPAYDETAIL().GetDealLogDetail(this.Code, this.PayType);
        }
    }

    private void BindDealLogMain()
    {
        int recordCount;
        DataSet dst = new BLL.IMPORTBILL().SP_DealLog_GetDealLog(1, 10, " and IB_ID='" + this.Code + "'", out recordCount);
        rptIMPORTBILL.DataSource = dst;
        rptIMPORTBILL.DataBind();
        if (rptIMPORTBILL.Items.Count > 0)
        {
            this.PayType = dst.Tables[0].Rows[0]["IB_PAYTYPE"].ToString();
        }
    }

    private void BindDealLogDetail()
    {
        int pageCount, rowCount;
        rptIMPORTBILL_ALIPAYDETAIL.DataSource = new BLL.IMPORTBILL_ALIPAYDETAIL().GetDealLogDetail(this.Code, this.PayType, GetStartIndex(AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize), AspNetPager1.PageSize, out rowCount);
        pageCount = rowCount / AspNetPager1.PageSize;
        rptIMPORTBILL_ALIPAYDETAIL.DataBind();
        AspNetPager1.RecordCount = rowCount;
    }

    protected void rptIMPORTBILL_ALIPAYDETAIL_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (ItemCommand != null)
            ItemCommand(source, e);
    }

    protected void btnMatchingOrder_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("700101", "00015"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        if (DealLogDetails != null)
        {
            #region 匹配
            MatchingOrder();
            BindDealLogDetail();
            #endregion

            #region 结算
            string user = Share.UserValue(0);
            StringBuilder sbCommandOfBStyle = new StringBuilder();
            StringBuilder sbCommandOfErp = new StringBuilder();
            /*foreach (RepeaterItem temp in rptIMPORTBILL_ALIPAYDETAIL.Items)
            {
                CheckBox chkMatching = (CheckBox)temp.FindControl("chkMatching");
                if (!chkMatching.Checked)
                {
                    continue;
                }
                Label lblCID = (Label)temp.FindControl("lblCID");

                ClearOrder(this.PayType, lblCID.Text, user, sbCommandOfBStyle, sbCommandOfErp);
            }*/
            DealLogDetails = new BLL.IMPORTBILL_ALIPAYDETAIL().GetDealLogDetail(this.Code, this.PayType);
            foreach (DataRow row in DealLogDetails.Tables[0].Rows)
            {
                if (row["IBAD_DO"].ToString()=="0")
                {
                    continue;
                }
                ClearOrder(this.PayType, row["IBAD_CID"].ToString(), user, sbCommandOfBStyle, sbCommandOfErp);
            }

            string strCommandOfBStyle = sbCommandOfBStyle.ToString();
            string strCommandOfErp = sbCommandOfErp.ToString();
            if (strCommandOfBStyle == "")
            {
                Share.Alert(this.Page, "所有订单已结算！");
            }
            char[] charToTrim = new char[] { '^' };
            string[] strArraySqlCommandArrayToUpdateBStyleDB = strCommandOfBStyle.TrimEnd(charToTrim).Split(charToTrim);
            string[] strArraySqlCommandArrayToUpdateErpDB = strCommandOfErp.TrimEnd(charToTrim).Split(charToTrim);


            LX_Manage.ERP.Service webService = new LX_Manage.ERP.Service();
            string strWebServiceKey = ConfigurationManager.AppSettings["WebServiceKey"].ToString();
            webService.UpdateBalanceAndUsableDeliverAmountMoreThanOneRecord(strWebServiceKey, strArraySqlCommandArrayToUpdateBStyleDB, strArraySqlCommandArrayToUpdateErpDB);
            BindDealLogDetail();

            Share.InsertLog("700101", "00015");

            Share.Alert(this.Page, "操作已成功！");
            #endregion
        }
        
    }



    private void MatchingOrder()
    {
        try
        {/*
            foreach (RepeaterItem temp in rptIMPORTBILL_ALIPAYDETAIL.Items)
            {
                CheckBox chkMatching = (CheckBox)temp.FindControl("chkMatching");
                if (chkMatching.Checked)
                {
                    continue;
                }
                Label lblCID = (Label)temp.FindControl("lblCID");
                Label lblDetailId = (Label)temp.FindControl("lblDetailId");
                Label lblIncome = (Label)temp.FindControl("lblIncome");
                if (lblCID.Text == "")
                {
                    continue;
                }
                
                new BLL.IMPORTBILL_ALIPAYDETAIL().MatchingOrder(lblCID.Text, this.PayType, Convert.ToDecimal(lblIncome.Text), this.Code, lblDetailId.Text);
            } 
          */
            foreach (DataRow row in DealLogDetails.Tables[0].Rows)
            {
                if (row["IBAD_DO"].ToString() == "1")
                {
                    continue;
                }
                if (row["IBAD_CID"].ToString() == "")
                {
                    continue;
                }
                new BLL.IMPORTBILL_ALIPAYDETAIL().MatchingOrder(row["IBAD_CID"].ToString(), this.PayType, Convert.ToDecimal(row["IBAD_IN"].ToString()), this.Code, row["IBAD_DETAILCODE"].ToString());
            }
        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }
    }
    public void ClearOrder(string payType, string cId, string operatorId, StringBuilder strCommandOfBStyle, StringBuilder strCommandOfErp)
    {
        int pageCount, recordCount;
        List<Model.PAYDETAIL> payDetail = new BLL.PAYDETAIL().GetList(10, 1, "PD_DEALDATE", false, " and PD_DEALID='" + cId + "' and PD_PAYTYPE='" + payType + "'", out pageCount, out recordCount);
        if (recordCount > 0)
        {
            int payDetailsRecordCount;
            List<Model.PAYDETAIL> payDetails = new BLL.PAYDETAIL().GetList(10, 1, "PD_DEALDATE", false, " and PD_ID='" + payDetail[0].PD_ID + "'", out pageCount, out payDetailsRecordCount);
            if (payDetailsRecordCount > 0)
            {
                foreach (Model.PAYDETAIL temp in payDetails)
                {
                    if (temp.PD_GET == 0)
                    {
                        return;
                    }
                }

                int orderDetailRecordCount;
                Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(payDetail[0].PD_ID);
                List<Model.ORDERDETAIL> orderDetails = new BLL.ORDERDETAIL().GetList(100, 1, " OD_DETAILID ", false, " and OD_ID='" + payDetail[0].PD_ID + "' ", out pageCount, out orderDetailRecordCount);
                if (order != null && orderDetails != null)
                {
                    if (order.ORDER_CLEAR == 1)
                    {
                        return;
                    }
                    if (orderDetails.Count == 0)
                    {
                        return;//throw new Exception("系统无法查询到该订单的明细，不能执行发货操作！");
                    }
                    if (order.ORDER_PAYAMT < order.ORDER_AAMT)
                    {
                        return;
                    }
                    BLL.Common.ADDLSH("700100");

                    Model.V_VIPSET userInfo = new BLL.V_VIPSET().GetModel(order.ORDER_CUSTOMERCODE);
                    if (userInfo == null)
                    {
                        throw new Exception("系统内无此会员信息！");
                    }
                    Model.V_VIP_ACCOUNT userAccount = new BLL.V_VIP_ACCOUNT().GetModel(userInfo.DM);
                    if (userInfo != null && userAccount != null)
                    {
                        //if (order.ORDER_TAMT <= userAccount.DQJE_1)
                        //{
                        StringBuilder strSqlToUpdateBStyleDB = new StringBuilder();
                        StringBuilder strSqlToUpdateErpDB = new StringBuilder();

                        //decimal points = Convert.ToDecimal(0.00);  //购物送积分改为开关控制，暂时全部在会员登陆或后台查会员信息的时候加 lyf 2009.02.24
                        //foreach (Model.ORDERDETAIL temp in orderDetails)
                        //{
                        //    points += temp.OD_ADDITG;
                        //}
                        int nonCouponPayDetailsPageCount, nonCouponPayDetailsRecordCount;
                        List<Model.PAYDETAIL> nonCouponPayDetails = new BLL.PAYDETAIL().GetList(10, 1, "PD_DEALDATE", false, " and PD_ID='" + order.ORDER_ID + "' and PD_PAYTYPE !='002'", out nonCouponPayDetailsPageCount, out nonCouponPayDetailsRecordCount);
                        decimal nonCouponPayDetailsAmount = 0.00M;
                        foreach (Model.PAYDETAIL temp in nonCouponPayDetails)
                        {
                            nonCouponPayDetailsAmount += temp.PD_GETAMT + temp.PD_HRAMT;
                        }
                        BLL.Promotion.BuildInitCouponSqlString(nonCouponPayDetailsAmount, order.ORDER_ID, order.ORDER_CUSTOMERCODE, strSqlToUpdateBStyleDB, strSqlToUpdateErpDB);
                        
                        //修改结算标志位

                        string sql = "";
                        if (nonCouponPayDetailsAmount - order.ORDER_AAMT >= 0)
                        {
                            sql = new BLL.IMPORTBILL_ALIPAYDETAIL().GetUpdateClearSql(order.ORDER_ID);
                            strSqlToUpdateBStyleDB.Append(sql);
                            strSqlToUpdateErpDB.Append("select 1|");
                        }
                        if (nonCouponPayDetailsAmount - order.ORDER_AAMT > 0)
                        {
                            
                            //string strUpdateVipSetSqlString = new BLL.V_VIPSET().BuildUpdateVipSetSqlString(0, 0, points, order.ORDER_CUSTOMERCODE);//购物送积分改为开关控制，暂时全部在会员登陆或后台查会员信息的时候加 lyf 2009.02.24
                            //strSqlToUpdateBStyleDB.Append(strUpdateVipSetSqlString);
                            //strSqlToUpdateErpDB.Append(strUpdateVipSetSqlString);

                            string strUpdateVipAccountSqlString = new BLL.V_VIP_ACCOUNT().BuildUpdateVipAccountSqlString(order.ORDER_CLEARAMT - order.ORDER_AAMT, userInfo.DM);
                            strSqlToUpdateBStyleDB.Append(strUpdateVipAccountSqlString);
                            strSqlToUpdateErpDB.Append("select 1|select 1|select 1|");
                            strSqlToUpdateErpDB.Append(strUpdateVipAccountSqlString);
                            strSqlToUpdateErpDB.Append("^");
                            
                            string user = Share.UserValue(0);
                            string strInsertBalanceManagementSqlString = new BLL.BALANCEADJUST().BuildInsertMainSqlString("007", order.ORDER_ID, user, user, order.ORDER_CUSTOMERCODE, order.ORDER_CLEARAMT - order.ORDER_AAMT);
                            strSqlToUpdateBStyleDB.Append(strInsertBalanceManagementSqlString);
                            strSqlToUpdateBStyleDB.Append("^");
                            //strSqlToUpdateErpDB.Append(strInsertBalanceManagementSqlString);
                            //strSqlToUpdateErpDB.Append("^");

                            
                        }
                        else
                        {
                            //string strUpdateVipSetSqlString = new BLL.V_VIPSET().BuildUpdateVipSetSqlString(0, 0, points, order.ORDER_CUSTOMERCODE);//购物送积分改为开关控制，暂时全部在会员登陆或后台查会员信息的时候加 lyf 2009.02.24
                            //strSqlToUpdateBStyleDB.Append(strUpdateVipSetSqlString);
                            //strSqlToUpdateBStyleDB.Append("^");
                            //strSqlToUpdateErpDB.Append(strUpdateVipSetSqlString);
                            //strSqlToUpdateErpDB.Append("^");
                        }
                        
                        string stringSqlToUpdateBStyleDB = strSqlToUpdateBStyleDB.ToString();
                        string stringSqlToUpdateErpDB = strSqlToUpdateErpDB.ToString();

                        strCommandOfBStyle.Append(stringSqlToUpdateBStyleDB);
                        strCommandOfErp.Append(stringSqlToUpdateErpDB);
                        //}
                        //else
                        //{
                        //    return;//throw new Exception("会员结余款金额小于本次发货金额，不能执行发货操作！");
                        //}
                    }
                    else
                    {
                        
                    }

                }
                else
                {
                    return;//throw new Exception("查询数据时出现错误，请重新执行发货操作！");
                }
                
            }
        }
    }
    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {
        BindDealLogDetail();
    }
    private int GetStartIndex(int pageIndex, int pageSize)
    {
        return 1 + (pageIndex - 1) * pageSize;
    }
}
